package com.haoxuewa.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.haoxuewa.service.MessageService;
import com.haoxuewa.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/backstage")
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    //获取站内用户列表
    //分页查询带上分页数请求
    @GetMapping("/getAllUserList")
    public String getAllUserList(@Param("pageNum") int pageNum) {
        System.out.println("ddddddddd");
        System.out.println(pageNum);
        JSONObject jsonObject = new JSONObject();
        int pageSize = 10;
        System.out.println(pageNum);
        IPage page = userService.selectAllUser(pageNum, pageSize);
        jsonObject.put("总页数", page.getPages());
        jsonObject.put("当前页数", page.getTotal());
        jsonObject.put("当前页面记录数量", page.getSize());
        jsonObject.put("resultList", page.getRecords());
        return jsonObject.toString();
    }

    //强制删除用户
    @PostMapping("/deleteUser")
    public String deleteUser(@RequestBody Map<String, String> map) {
        JSONObject jsonObject = new JSONObject();
        if (userService.deleteUser(map.get("name"))) jsonObject.put("result", "删除成功");
        else jsonObject.put("result", "删除失败");
        return jsonObject.toString();
    }

    @PostMapping("/addUser")
    public String addUser(@RequestBody Map<String, String> map) {
        JSONObject jsonObject = new JSONObject();
        if (userService.addUser(map.get("userName"), map.get("password"), map.get("gender"), map.get("birthday"))) {
            jsonObject.put("code", "200");
        } else {
            jsonObject.put("code", "404");
        }
        return jsonObject.toString();
    }

    //站内用户性别统计
    @GetMapping("/getGenderQuantity")
    public String getGenderQuantity() {
        JSONObject jsonObject = new JSONObject();
        List<Map<String, Object>> list = userService.userGenderQuantity();
        for (Map<String, Object> map : list) {
            if (!list.get(0).containsKey("gender")) {
                map.put("gender", "未知");
            }
        }
        jsonObject.put("data", list);
        System.out.println(jsonObject.toString());
        return jsonObject.toString();
    }

}
